import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../serve/file_serve.dart';
import '../widgets/knowledge_graph_widget.dart';
import '../widgets/simple_knowledge_graph_widget.dart';

/// 知识图谱详情页面
class KnowledgeGraphPage extends StatefulWidget {
  final FileServe fileServe;

  const KnowledgeGraphPage({
    Key? key,
    required this.fileServe,
  }) : super(key: key);

  @override
  _KnowledgeGraphPageState createState() => _KnowledgeGraphPageState();
}

class _KnowledgeGraphPageState extends State<KnowledgeGraphPage>
    with TickerProviderStateMixin {
  late AnimationController _fadeController;
  late Animation<double> _fadeAnimation;
  
  bool _isLoading = true;
  bool _usePhysicsEngine = false; // 默认使用简化版
  String _searchQuery = '';
  KnowledgeNode? _selectedNode;
  SimpleKnowledgeNode? _selectedSimpleNode;
  Map<String, List<String>> _tagData = {};
  List<Map<String, dynamic>> _tagStatistics = [];
  List<String> _filteredTags = [];
  final TextEditingController _searchController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _fadeController = AnimationController(
      duration: Duration(milliseconds: 800),
      vsync: this,
    );
    _fadeAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _fadeController,
      curve: Curves.easeInOut,
    ));
    
    _loadData();
  }

  @override
  void dispose() {
    _fadeController.dispose();
    _searchController.dispose();
    super.dispose();
  }

  Future<void> _loadData() async {
    try {
      // 加载标签数据
      final tagData = await widget.fileServe.getGlobalTags();
      final tagStats = await widget.fileServe.getTagStatistics();
      
      setState(() {
        _tagData = tagData;
        _tagStatistics = tagStats;
        _filteredTags = tagData.keys.toList();
        _isLoading = false;
      });
      
      _fadeController.forward();
    } catch (e) {
      print('加载知识图谱数据失败: $e');
      setState(() {
        _isLoading = false;
      });
    }
  }

  void _onSearchChanged(String query) {
    setState(() {
      _searchQuery = query;
      if (query.isEmpty) {
        _filteredTags = _tagData.keys.toList();
      } else {
        _filteredTags = _tagData.keys
            .where((tag) => tag.toLowerCase().contains(query.toLowerCase()))
            .toList();
      }
    });
  }

  void _onNodeTap(dynamic node) {
    setState(() {
      if (node is KnowledgeNode) {
        _selectedNode = node;
        _selectedSimpleNode = null;
      } else if (node is SimpleKnowledgeNode) {
        _selectedSimpleNode = node;
        _selectedNode = null;
      }
    });
    _showNodeDetails(node);
  }

  void _showNodeDetails(dynamic node) {
    final String label;
    final int documentCount;
    final List<String> documents;
    
    if (node is String) {
      // 来自标签列表的点击
      label = node;
      documentCount = _tagData[label]?.length ?? 0;
      documents = _tagData[label] ?? [];
    } else {
      // 来自图谱节点的点击
      label = node.label as String;
      documentCount = node.documentCount as int;
      documents = node.documents as List<String>;
    }

    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => _buildNodeDetailsSheet(label, documentCount, documents),
    );
  }

  Widget _buildNodeDetailsSheet(String label, int documentCount, List<String> documents) {
    return Container(
      height: MediaQuery.of(context).size.height * 0.7,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(24),
          topRight: Radius.circular(24),
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 20,
            offset: Offset(0, -5),
          ),
        ],
      ),
      child: Column(
        children: [
          // 拖拽指示器
          Container(
            margin: EdgeInsets.only(top: 12),
            width: 40,
            height: 4,
            decoration: BoxDecoration(
              color: Colors.grey[300],
              borderRadius: BorderRadius.circular(2),
            ),
          ),
          
          // 标题栏
          Padding(
            padding: EdgeInsets.all(24),
            child: Row(
              children: [
                Container(
                  padding: EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      colors: [Color(0xFF667eea), Color(0xFF764ba2)],
                    ),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Icon(Icons.local_offer, color: Colors.white, size: 24),
                ),
                SizedBox(width: 16),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        label,
                        style: TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.bold,
                          color: Colors.grey[800],
                        ),
                      ),
                      SizedBox(height: 4),
                      Text(
                        '$documentCount 个相关文档',
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.grey[600],
                        ),
                      ),
                    ],
                  ),
                ),
                IconButton(
                  onPressed: () {
                    Clipboard.setData(ClipboardData(text: label));
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(
                        content: Text('标签已复制到剪贴板'),
                        backgroundColor: Colors.green,
                        behavior: SnackBarBehavior.floating,
                      ),
                    );
                  },
                  icon: Icon(Icons.copy, color: Colors.grey[600]),
                ),
              ],
            ),
          ),
          
          Divider(height: 1),
          
          // 文档列表
          Expanded(
            child: ListView.builder(
              padding: EdgeInsets.all(24),
              itemCount: documents.length,
              itemBuilder: (context, index) {
                final doc = documents[index];
                return Container(
                  margin: EdgeInsets.only(bottom: 12),
                  decoration: BoxDecoration(
                    color: Colors.grey[50],
                    borderRadius: BorderRadius.circular(12),
                    border: Border.all(color: Colors.grey[200]!),
                  ),
                  child: ListTile(
                    leading: Container(
                      padding: EdgeInsets.all(8),
                      decoration: BoxDecoration(
                        color: Colors.blue[100],
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Icon(
                        _getFileIcon(doc),
                        color: Colors.blue[600],
                        size: 20,
                      ),
                    ),
                    title: Text(
                      doc,
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    subtitle: Text(
                      _getFileType(doc),
                      style: TextStyle(
                        fontSize: 12,
                        color: Colors.grey[600],
                      ),
                    ),
                    trailing: Icon(Icons.arrow_forward_ios, size: 16, color: Colors.grey[400]),
                    onTap: () {
                      // TODO: 跳转到文档详情
                      Navigator.pop(context);
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(
                          content: Text('文档功能开发中...'),
                          backgroundColor: Colors.orange,
                        ),
                      );
                    },
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  IconData _getFileIcon(String fileName) {
    final extension = fileName.split('.').last.toLowerCase();
    switch (extension) {
      case 'pdf':
        return Icons.picture_as_pdf;
      case 'md':
        return Icons.description;
      case 'txt':
        return Icons.text_snippet;
      case 'docx':
      case 'doc':
        return Icons.article;
      case 'xlsx':
      case 'xls':
        return Icons.table_chart;
      case 'pptx':
      case 'ppt':
        return Icons.slideshow;
      default:
        return Icons.insert_drive_file;
    }
  }

  String _getFileType(String fileName) {
    final extension = fileName.split('.').last.toLowerCase();
    switch (extension) {
      case 'pdf':
        return 'PDF 文档';
      case 'md':
        return 'Markdown 文件';
      case 'txt':
        return '文本文件';
      case 'docx':
      case 'doc':
        return 'Word 文档';
      case 'xlsx':
      case 'xls':
        return 'Excel 表格';
      case 'pptx':
      case 'ppt':
        return 'PowerPoint 演示';
      default:
        return '未知类型';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[50],
      body: CustomScrollView(
        slivers: [
          // 自定义导航栏
          SliverAppBar(
            expandedHeight: 120,
            floating: false,
            pinned: true,
            backgroundColor: Colors.transparent,
            elevation: 0,
            flexibleSpace: FlexibleSpaceBar(
              background: Container(
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    colors: [
                      Color(0xFF667eea),
                      Color(0xFF764ba2),
                    ],
                  ),
                ),
                child: SafeArea(
                  child: Padding(
                    padding: EdgeInsets.symmetric(horizontal: 20),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.end,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            IconButton(
                              onPressed: () => Navigator.pop(context),
                              icon: Icon(Icons.arrow_back, color: Colors.white),
                            ),
                            Expanded(
                              child: Text(
                                '知识图谱',
                                style: TextStyle(
                                  fontSize: 24,
                                  fontWeight: FontWeight.bold,
                                  color: Colors.white,
                                ),
                              ),
                            ),
                            // 切换模式按钮
                            IconButton(
                              onPressed: () {
                                setState(() {
                                  _usePhysicsEngine = !_usePhysicsEngine;
                                });
                                ScaffoldMessenger.of(context).showSnackBar(
                                  SnackBar(
                                    content: Text(_usePhysicsEngine ? '已切换到动态模式' : '已切换到静态模式'),
                                    duration: Duration(seconds: 1),
                                  ),
                                );
                              },
                              icon: Icon(
                                _usePhysicsEngine ? Icons.pause : Icons.play_arrow,
                                color: Colors.white,
                              ),
                              tooltip: _usePhysicsEngine ? '切换到静态模式' : '切换到动态模式',
                            ),
                          ],
                        ),
                        SizedBox(height: 12),
                      ],
                    ),
                  ),
                ),
              ),
            ),
            leading: Container(), // 隐藏默认返回按钮
          ),
          
          if (_isLoading)
            SliverFillRemaining(
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    CircularProgressIndicator(),
                    SizedBox(height: 16),
                    Text(
                      '正在构建知识图谱...',
                      style: TextStyle(
                        fontSize: 16,
                        color: Colors.grey[600],
                      ),
                    ),
                  ],
                ),
              ),
            )
          else
            SliverToBoxAdapter(
              child: FadeTransition(
                opacity: _fadeAnimation,
                child: Padding(
                  padding: EdgeInsets.all(20),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 统计卡片
                      _buildStatisticsCards(),
                      SizedBox(height: 24),
                      
                      // 搜索栏
                      _buildSearchBar(),
                      SizedBox(height: 24),
                      
                      // 知识图谱
                      _buildKnowledgeGraph(),
                      SizedBox(height: 24),
                      
                      // 标签列表
                      _buildTagsList(),
                    ],
                  ),
                ),
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildStatisticsCards() {
    final totalTags = _tagData.length;
    final totalDocs = _tagData.values.expand((docs) => docs).toSet().length;
    final avgDocsPerTag = totalTags > 0 ? (totalDocs / totalTags).toStringAsFixed(1) : '0';

    return Row(
      children: [
        Expanded(
          child: _buildStatCard(
            icon: Icons.local_offer,
            title: '标签总数',
            value: totalTags.toString(),
            color: Colors.blue,
          ),
        ),
        SizedBox(width: 12),
        Expanded(
          child: _buildStatCard(
            icon: Icons.description,
            title: '文档总数',
            value: totalDocs.toString(),
            color: Colors.green,
          ),
        ),
        SizedBox(width: 12),
        Expanded(
          child: _buildStatCard(
            icon: Icons.trending_up,
            title: '平均关联',
            value: avgDocsPerTag,
            color: Colors.orange,
          ),
        ),
      ],
    );
  }

  Widget _buildStatCard({
    required IconData icon,
    required String title,
    required String value,
    required Color color,
  }) {
    return Container(
      padding: EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: color.withOpacity(0.1),
            blurRadius: 10,
            offset: Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        children: [
          Container(
            padding: EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: color.withOpacity(0.1),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Icon(icon, color: color, size: 20),
          ),
          SizedBox(height: 8),
          Text(
            value,
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: Colors.grey[800],
            ),
          ),
          Text(
            title,
            style: TextStyle(
              fontSize: 12,
              color: Colors.grey[600],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSearchBar() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: Offset(0, 4),
          ),
        ],
      ),
      child: TextField(
        controller: _searchController,
        onChanged: _onSearchChanged,
        decoration: InputDecoration(
          hintText: '搜索标签...',
          prefixIcon: Icon(Icons.search, color: Colors.grey[400]),
          suffixIcon: _searchQuery.isNotEmpty
              ? IconButton(
                  onPressed: () {
                    _searchController.clear();
                    _onSearchChanged('');
                  },
                  icon: Icon(Icons.clear, color: Colors.grey[400]),
                )
              : null,
          border: InputBorder.none,
          contentPadding: EdgeInsets.symmetric(horizontal: 16, vertical: 16),
          hintStyle: TextStyle(color: Colors.grey[400]),
        ),
      ),
    );
  }

  Widget _buildKnowledgeGraph() {
    return Container(
      height: 400,
      width: double.infinity,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 15,
            offset: Offset(0, 5),
          ),
        ],
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(20),
        child: LayoutBuilder(
          builder: (context, constraints) {
            print('知识图谱容器尺寸: ${constraints.maxWidth} x ${constraints.maxHeight}');
            return _usePhysicsEngine
                ? KnowledgeGraphWidget(
                    fileServe: widget.fileServe,
                    width: constraints.maxWidth,
                    height: constraints.maxHeight,
                    showLabels: true,
                    enableInteraction: true,
                    onNodeTap: _onNodeTap,
                  )
                : SimpleKnowledgeGraphWidget(
                    fileServe: widget.fileServe,
                    width: constraints.maxWidth,
                    height: constraints.maxHeight,
                    showLabels: true,
                    onNodeTap: _onNodeTap,
                  );
          },
        ),
      ),
    );
  }

  Widget _buildTagsList() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Text(
              '标签列表',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
                color: Colors.grey[800],
              ),
            ),
            Spacer(),
            Text(
              '${_filteredTags.length} 个标签',
              style: TextStyle(
                fontSize: 14,
                color: Colors.grey[600],
              ),
            ),
          ],
        ),
        SizedBox(height: 16),
        
        if (_filteredTags.isEmpty)
          Container(
            width: double.infinity,
            padding: EdgeInsets.all(32),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(16),
              border: Border.all(color: Colors.grey[200]!),
            ),
            child: Column(
              children: [
                Icon(Icons.search_off, size: 48, color: Colors.grey[400]),
                SizedBox(height: 12),
                Text(
                  '没有找到匹配的标签',
                  style: TextStyle(
                    fontSize: 16,
                    color: Colors.grey[500],
                    fontWeight: FontWeight.w500,
                  ),
                ),
                SizedBox(height: 8),
                Text(
                  '尝试使用不同的关键词搜索',
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey[400],
                  ),
                ),
              ],
            ),
          )
        else
          ListView.builder(
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            itemCount: _filteredTags.length,
            itemBuilder: (context, index) {
              final tag = _filteredTags[index];
              final docCount = _tagData[tag]?.length ?? 0;
              final docs = _tagData[tag] ?? [];
              
              return Container(
                margin: EdgeInsets.only(bottom: 12),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(16),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.03),
                      blurRadius: 8,
                      offset: Offset(0, 2),
                    ),
                  ],
                ),
                child: ListTile(
                  contentPadding: EdgeInsets.symmetric(horizontal: 20, vertical: 12),
                  leading: Container(
                    padding: EdgeInsets.all(10),
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        colors: [
                          Color(0xFF667eea).withOpacity(0.8),
                          Color(0xFF764ba2).withOpacity(0.8),
                        ],
                      ),
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: Icon(Icons.local_offer, color: Colors.white, size: 20),
                  ),
                  title: Text(
                    tag,
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w600,
                      color: Colors.grey[800],
                    ),
                  ),
                  subtitle: Text(
                    '$docCount 个相关文档',
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.grey[600],
                    ),
                  ),
                  trailing: Icon(Icons.arrow_forward_ios, size: 16, color: Colors.grey[400]),
                  onTap: () => _showNodeDetails(tag),
                ),
              );
            },
          ),
      ],
    );
  }
} 